package com.chart.web.controller.common;

import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chart.chart.domian.ChartConfigsUser;
import com.chart.chart.mapper.ChartConfigsUserMapper;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.system.domain.SysUserOrder;
import com.chart.system.service.ISysUserOrderService;
import com.chart.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.bouncycastle.jcajce.provider.symmetric.RC6;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.chart.common.config.ChartConfig;
import com.chart.common.constant.Constants;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.StringUtils;
import com.chart.common.utils.file.FileUploadUtils;
import com.chart.common.utils.file.FileUtils;
import com.chart.framework.config.ServerConfig;

import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.Blob;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 通用请求处理
 *
 * @author chart
 */
@Api(tags = "公共模块")
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = ChartConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = ChartConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = ChartConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = ChartConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * base64转svg
     */
    @PostMapping("/base64ToSVG")
    public void Base64ToSVG(String str, String filename, HttpServletResponse response) throws Exception {
        try {
            // 解码Base64字符串
            byte[] decodedBytes = Base64.getDecoder().decode(str);

            filename = filename + ".svg";
            // 设置响应头
            response.setContentType("image/svg+xml");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            // 将字节数组写入响应输出流
            OutputStream os = response.getOutputStream();
            os.write(decodedBytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            System.err.println("文件写入错误: " + e.getMessage());
        }
    }

    @Resource
    private ChartConfigsUserMapper chartConfigsUserMapper;

    /**
     * |
     * 将数据库中的base64图片数据保存到本地
     * 测试本地路径:"/Users/kismet/Desktop/workspace/photo"
     *
     * @throws IOException
     */
    @PostMapping("/downloadImages")
    public void Base64ToPNG() throws IOException {
        List<String> newStr = getBase64StringList();
        String outputDirectory = "/Users/kismet/Desktop/workspace/photo";
        try {
            saveBase64ImagesToDirectory(newStr, outputDirectory);
            System.out.println("所有图片已成功保存到：" + outputDirectory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> getBase64StringList() {
        LambdaQueryWrapper<ChartConfigsUser> lambdaQueryWrapper = Wrappers.lambdaQuery();
        List<ChartConfigsUser> base64List = chartConfigsUserMapper.selectList(lambdaQueryWrapper);
        List<String> strList = new ArrayList<>();
        base64List.forEach(c -> {
            strList.add(c.getChartCover());
        });
        List<String> newStr = strList.stream().map(str -> {
            if (str.startsWith("data:image/png;base64,")) {
                return str.substring("data:image/png;base64,".length());
            }
            return str;
        }).collect(Collectors.toList());
        return newStr;
    }

    private void saveBase64ImagesToDirectory(List<String> strList, String outputDirectory) throws IOException {

        int count = 1;
        for (String base64String : strList) {
            byte[] imageBytes = Base64.getDecoder().decode(base64String);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(bis);
            String outputPath = outputDirectory + File.separator + "image" + count + ".png";
            File outputFile = new File(outputPath);
            ImageIO.write(image, "png", outputFile);
            count++;
        }
    }

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserOrderService userOrderService;

    /**
     * 手动刷新vip状态
     * @return
     */
    @ApiOperation("手动刷新VIP状态")
    @GetMapping("/refresh")
    public AjaxResult refreshVIP() {
        List<SysUser> commonUsers = new ArrayList<>();
        ArrayList<SysUser> vipUsers = new ArrayList<>();
        //获取所有会员数据
        List<SysUser> VIPList = userService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getIsVip, 1));
        VIPList.forEach(e -> {
            //根据id去查询vip订单数据
            SysUserOrder userOrder = userOrderService.getOne(new LambdaQueryWrapper<SysUserOrder>().eq(SysUserOrder::getUserId, e.getUserId()));
            //如果数据存在
            if (!ObjectUtils.isEmpty(userOrder)) {
                //获取vip过期时间比较
                LocalDateTime expirTime = userOrder.getExpirationTime();
                LocalDateTime now = LocalDateTime.now();
                if (expirTime.isBefore(now)) {
                    e.setIsVip(0);
                    commonUsers.add(e);
                }else {
                    e.setIsVip(1);
                    vipUsers.add(e);
                }
            }
        });

        userService.saveOrUpdateBatch(commonUsers);
        userService.saveOrUpdateBatch(vipUsers);
        return AjaxResult.success();
    }


//    @GetMapping("/resource")
//    public Blob resourceD(String resource, HttpServletRequest request, HttpServletResponse response)throws Exception
//    {
//        String filePath = protocol;
//        InputStream in = new FileDataSource(filePath).getInputStream();
//        XWPFDocument document = new XWPFDocument(in);
//
//        // 将Word文档写入字节流
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        document.write(out);
//        byte[] byteArray = out.toByteArray();
//
//        // 关闭流
//        in.close();
//        out.close();
//
//        // 将字节流转换为Blob对象
//        Blob blob = new SerialBlob(byteArray);
//        return blob;
//    }

//    @GetMapping("/resource1")
//    public void resourceD( HttpServletRequest request, HttpServletResponse response)throws Exception
//    {
//        String filePath = protocol;
//        // 设置内容类型和打开文件输出流
//        response.setContentType("text/plain");
//        FileInputStream fis = null;
//        try {
//            // 打开文件输入流
//            File file = new File(filePath);
//            fis = new FileInputStream(file);
//
//            // 创建输出流
//            ServletOutputStream outStream = response.getOutputStream();
//
//            // 创建缓冲区
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//
//            // 读取并输出文件内容
//            while ((bytesRead = fis.read(buffer)) != -1) {
//                outStream.write(buffer, 0, bytesRead);
//            }
//
//            // 刷新缓冲区
//            outStream.flush();
//        } finally {
//            // 关闭文件输入流
//            if (fis != null) {
//                fis.close();
//            }
//        }
//    }

}
